﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Genesis.Application.Forms
{
    public partial class TweetForm : Genesis.Client.Common.Classes.MdiChildBase, Genesis.Common.Interfaces.IMdiChild
    {
        public TweetForm()
        {
            InitializeComponent();

            LinqToTwitterWrapper.SignOn();

            tweemer_Tick(this, null);
        }

        private void tweemer_Tick(object sender, EventArgs e)
        {
            tweemer.Enabled = false;

            LinqToTwitter.TwitterQueryable<LinqToTwitter.Status> statusTweets = LinqToTwitterWrapper.GetPublicTweets();

            foreach (LinqToTwitter.Status status in statusTweets)
            {
                string tweet = string.Empty;

                tweet = string.Format("{0} said {1} - {2} ago",
                    status.User.Name,
                    status.Text,
                    GetTweetTime(status));

                if (!tweets.Items.Contains(tweet))
                    tweets.Items.Insert(0, tweet);
            }

            tweemer.Enabled = true;
        }

        private static string GetTweetTime(LinqToTwitter.Status status)
        {
            TimeSpan tweetTime = new TimeSpan(DateTime.Now.Ticks - status.CreatedAt.Ticks);

            string returnValue = string.Empty;

            if (tweetTime.TotalSeconds < 60)
            {
                returnValue = string.Format("{0} seconds ago",
                    tweetTime.TotalSeconds);
            }
            else if (tweetTime.TotalMinutes < 60)
            {
                returnValue = string.Format("{0} minutes ago",
                    tweetTime.TotalMinutes);
            }
            else if (tweetTime.TotalHours < 24)
            {
                returnValue = string.Format("{0} hours ago",
                    tweetTime.TotalHours);
            }
            else
            {
                returnValue = string.Format("{0} days ago",
                    tweetTime.TotalDays);
            }

            return returnValue;
        }

        private void tweetton_Click(object sender, EventArgs e)
        {
            LinqToTwitterWrapper.UpdateStatus(tweetBox.Text);
            tweetBox.Text = string.Empty;

            tweemer_Tick(sender, e);
        }

        private void tweetBox_TextChanged(object sender, EventArgs e)
        {
            int tweetLengthCount = 140;

            int tweetTextLength = tweetBox.Text.Length;

            tweetLength.Text = string.Format("{0}",
                tweetLengthCount - tweetTextLength);

            if ((tweetLengthCount - tweetTextLength) < 0)
            {
                tweetBox.Text = tweetBox.Text.Substring(1, 140);
            }
        }
    }
}
